<template>
	<view class="container">
		<!-- 顶部导航 -->
		<view class="header">
			<view class="header-left">
				<image class="user-avatar" :src="userInfo.avatar || '/static/default-avatar.png'" mode="aspectFill"></image>
				<text class="user-name">{{userInfo.name || '用户'}}</text>
			</view>
			<view class="header-right">
				<uni-icons type="settings" size="20" @click="showSettings"></uni-icons>
			</view>
		</view>

		<!-- 虚拟形象区域 -->
		<view class="avatar-section">
			<view class="virtual-avatar">
				<!-- 虚拟形象主体 -->
				<view class="avatar-face">
					<view class="avatar-eyes">
						<view class="eye left-eye" :class="{'blink': isBlinking}"></view>
						<view class="eye right-eye" :class="{'blink': isBlinking}"></view>
					</view>
					<view class="avatar-mouth" :class="{'talking': isTalking}"></view>
				</view>
				
				<!-- 状态指示 -->
				<view class="avatar-status">
					<view class="status-dot"></view>
					<text>在线</text>
				</view>
			</view>
			
			<view class="avatar-greeting">
				<text class="greeting-text">你好{{userInfo.name ? '，' + userInfo.name : ''}}！我是你的学习搭子</text>
				<text class="greeting-subtext">有什么学习问题都可以问我哦</text>
			</view>
		</view>

		<!-- 对话区域 -->
		<view class="chat-section">
			<scroll-view class="chat-messages" scroll-y="true" :scroll-into-view="'msg-' + (messages.length - 1)">
				<view v-for="(message, index) in messages" :key="index" :id="'msg-' + index" 
					  :class="['message', message.type]">
					
					<!-- AI消息 -->
					<view v-if="message.type === 'ai'" class="message-content ai-message">
						<image class="message-avatar" src="/static/ai-avatar.png" mode="aspectFill"></image>
						<view class="message-bubble">
							<text>{{message.content}}</text>
							<view class="message-time">{{message.time}}</view>
						</view>
					</view>
					
					<!-- 用户消息 -->
					<view v-else class="message-content user-message">
						<view class="message-bubble">
							<text>{{message.content}}</text>
							<view class="message-time">{{message.time}}</view>
						</view>
						<image class="message-avatar" :src="userInfo.avatar || '/static/default-avatar.png'" mode="aspectFill"></image>
					</view>
				</view>
			</scroll-view>
		</view>

		<!-- 输入区域 -->
		<view class="input-section">
			<view class="input-container">
				<view class="input-left">
					<uni-icons type="plus" size="24" color="#666" @click="showMoreOptions"></uni-icons>
				</view>
				
				<view class="input-center">
					<input type="text" v-model="inputMessage" placeholder="输入你的问题..." 
						   @confirm="sendMessage" :focus="autoFocus" />
				</view>
				
				<view class="input-right">
					<button class="send-btn" @click="sendMessage" :disabled="!inputMessage.trim()">
						<uni-icons type="paperplane" size="20" :color="inputMessage.trim() ? '#fff' : '#ccc'"></uni-icons>
					</button>
				</view>
			</view>
			
			<!-- 快捷问题 -->
			<view class="quick-questions">
				<scroll-view class="quick-scroll" scroll-x="true">
					<view class="quick-question" v-for="(question, index) in quickQuestions" :key="index" 
						  @click="sendQuickQuestion(question)">
						<text>{{question}}</text>
					</view>
				</scroll-view>
			</view>
		</view>

		<!-- 加载状态 -->
		<view class="loading" v-if="isLoading">
			<view class="loading-dots">
				<view class="dot"></view>
				<view class="dot"></view>
				<view class="dot"></view>
			</view>
			<text>AI正在思考中...</text>
		</view>

		<!-- 设置面板 -->
		<uni-popup ref="settingsPopup" type="bottom">
			<view class="settings-panel">
				<view class="panel-header">
					<text>设置</text>
					<uni-icons type="close" size="20" @click="closeSettings"></uni-icons>
				</view>
				<view class="panel-content">
					<view class="setting-item">
						<text>虚拟形象</text>
						<switch :checked="true" @change="toggleAvatar" />
					</view>
					<view class="setting-item">
						<text>声音反馈</text>
						<switch :checked="false" @change="toggleSound" />
					</view>
					<view class="setting-item">
						<text>清除聊天记录</text>
						<uni-icons type="trash" size="18" color="#ff4d4f" @click="clearChat" />
					</view>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				userInfo: {
					name: '',
					avatar: '/static/default-avatar.png'
				},
				messages: [
					{
						type: 'ai',
						content: '你好！我是你的智能学习搭子，我们可以一起讨论学习问题、制定学习计划，或者聊聊学习中的困惑。',
						time: '刚刚'
					}
				],
				inputMessage: '',
				isLoading: false,
				isBlinking: false,
				isTalking: false,
				autoFocus: true,
				quickQuestions: [
					'如何提高学习效率？',
					'推荐一些学习方法',
					'帮我制定学习计划',
					'数学怎么学更好？',
					'英语学习技巧'
				]
			}
		},
		onLoad() {
			// 加载用户信息
			const savedInfo = uni.getStorageSync('userInfo');
			if (savedInfo) {
				this.userInfo = { ...this.userInfo, ...savedInfo };
			}
			
			// 启动眨眼动画
			this.startBlinking();
			
			// 加载历史消息
			const history = uni.getStorageSync('chatHistory');
			if (history && history.length > 0) {
				this.messages = history;
			}
		},
		methods: {
			// 虚拟形象动画
			startBlinking() {
				setInterval(() => {
					this.isBlinking = true;
					setTimeout(() => {
						this.isBlinking = false;
					}, 200);
				}, 3000 + Math.random() * 2000);
			},

			// 发送消息
			async sendMessage() {
				if (!this.inputMessage.trim()) return;
				
				const userMessage = this.inputMessage.trim();
				this.inputMessage = '';
				
				// 添加用户消息
				const userMsg = {
					type: 'user',
					content: userMessage,
					time: this.getCurrentTime()
				};
				this.messages.push(userMsg);
				
				// 显示加载状态
				this.isLoading = true;
				this.isTalking = true;
				
				// 模拟AI思考
				await new Promise(resolve => setTimeout(resolve, 1000 + Math.random() * 1000));
				
				// 生成AI回复
				const aiResponse = this.generateAIResponse(userMessage);
				const aiMsg = {
					type: 'ai',
					content: aiResponse,
					time: '刚刚'
				};
				
				this.messages.push(aiMsg);
				this.isLoading = false;
				
				// 停止说话动画
				setTimeout(() => {
					this.isTalking = false;
				}, 1000);
				
				// 保存聊天记录
				uni.setStorageSync('chatHistory', this.messages);
			},

			// 发送快捷问题
			sendQuickQuestion(question) {
				this.inputMessage = question;
				this.sendMessage();
			},

			// 生成AI回复
			generateAIResponse(userMessage) {
				const responses = {
					'学习效率': '提高学习效率可以尝试番茄工作法：25分钟专注学习，5分钟休息。同时要保证充足的睡眠和适当的运动。',
					'学习方法': '推荐主动回忆法：学完知识后主动回忆，而不是被动重复阅读。还有费曼技巧：尝试用简单语言解释复杂概念。',
					'学习计划': '制定学习计划要具体可行。建议先确定目标，然后分解任务，设置时间节点，最后定期回顾调整。',
					'数学': '数学学习要注重理解概念，多做练习题，建立知识体系。遇到难题不要怕，可以拆解问题一步步解决。',
					'英语': '英语学习要多听多说，可以通过看英文电影、听英文歌曲来培养语感。背单词要结合语境记忆。'
				};
				
				// 匹配关键词
				for (const [key, response] of Object.entries(responses)) {
					if (userMessage.includes(key)) {
						return response;
					}
				}
				
				// 默认回复
				const defaultResponses = [
					'这个问题很有意思！让我想想怎么帮你...',
					'我明白你的困惑了，我们可以从这几个方面来讨论：',
					'关于这个问题，我的建议是：首先要明确学习目标，然后制定具体计划。',
					'很好的问题！这让我想到了一些相关的学习策略。'
				];
				
				return defaultResponses[Math.floor(Math.random() * defaultResponses.length)];
			},

			// 获取当前时间
			getCurrentTime() {
				const now = new Date();
				return `${now.getHours().toString().padStart(2, '0')}:${now.getMinutes().toString().padStart(2, '0')}`;
			},

			// 设置相关
			showSettings() {
				this.$refs.settingsPopup.open();
			},

			closeSettings() {
				this.$refs.settingsPopup.close();
			},

			toggleAvatar(e) {
				console.log('切换虚拟形象:', e.detail.value);
			},

			toggleSound(e) {
				console.log('切换声音:', e.detail.value);
			},

			clearChat() {
				uni.showModal({
					title: '确认清除',
					content: '确定要清除所有聊天记录吗？',
					success: (res) => {
						if (res.confirm) {
							this.messages = [{
								type: 'ai',
								content: '聊天记录已清除，我们可以重新开始对话了！',
								time: '刚刚'
							}];
							uni.removeStorageSync('chatHistory');
							this.closeSettings();
						}
					}
				});
			},

			showMoreOptions() {
				uni.showActionSheet({
					itemList: ['拍照', '从相册选择', '文件', '位置'],
					success: (res) => {
						console.log('选择了第' + (res.tapIndex + 1) + '个按钮');
					}
				});
			}
		}
	}
</script>

<style>
	.container {
		height: 100vh;
		display: flex;
		flex-direction: column;
		background: #f5f7fa;
	}
	
	/* 头部导航 */
	.header {
		padding: 15px 20px;
		background: white;
		display: flex;
		align-items: center;
		justify-content: space-between;
		border-bottom: 1px solid #eee;
	}
	
	.header-left {
		display: flex;
		align-items: center;
		gap: 10px;
	}
	
	.user-avatar {
		width: 36px;
		height: 36px;
		border-radius: 50%;
	}
	
	.user-name {
		font-size: 16px;
		font-weight: 500;
		color: #333;
	}
	
	/* 虚拟形象区域 */
	.avatar-section {
		padding: 20px;
		background: white;
		display: flex;
		align-items: center;
		gap: 15px;
		border-bottom: 1px solid #eee;
	}
	
	.virtual-avatar {
		position: relative;
		width: 80px;
		height: 80px;
	}
	
	.avatar-face {
		width: 60px;
		height: 60px;
		background: linear-gradient(135deg, #6e8efb, #a777e3);
		border-radius: 50%;
		position: relative;
		margin: 0 auto;
	}
	
	.avatar-eyes {
		position: absolute;
		top: 20px;
		left: 0;
		right: 0;
		display: flex;
		justify-content: space-around;
	}
	
	.eye {
		width: 8px;
		height: 8px;
		background: #333;
		border-radius: 50%;
		position: relative;
	}
	
	.eye.blink {
		height: 2px;
	}
	
	.avatar-mouth {
		position: absolute;
		bottom: 15px;
		left: 50%;
		transform: translateX(-50%);
		width: 20px;
		height: 4px;
		background: #333;
		border-radius: 2px;
		transition: all 0.3s ease;
	}
	
	.avatar-mouth.talking {
		height: 8px;
		animation: talk 0.5s infinite alternate;
	}
	
	@keyframes talk {
		0% { width: 15px; }
		100% { width: 25px; }
	}
	
	.avatar-status {
		position: absolute;
		top: -5px;
		right: -5px;
		background: white;
		padding: 4px 8px;
		border-radius: 12px;
		font-size: 12px;
		color: #52c41a;
		display: flex;
		align-items: center;
		gap: 4px;
		box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
	}
	
	.status-dot {
		width: 6px;
		height: 6px;
		background: #52c41a;
		border-radius: 50%;
	}
	
	.avatar-greeting {
		flex: 1;
	}
	
	.greeting-text {
		display: block;
		font-size: 16px;
		font-weight: 500;
		color: #333;
		margin-bottom: 4px;
	}
	
	.greeting-subtext {
		font-size: 14px;
		color: #666;
	}
	
	/* 对话区域 */
	.chat-section {
		flex: 1;
		padding: 15px;
		overflow: hidden;
	}
	
	.chat-messages {
		height: 100%;
	}
	
	.message {
		margin-bottom: 15px;
	}
	
	.message-content {
		display: flex;
		align-items: flex-end;
	}
	
	.ai-message {
		justify-content: flex-start;
	}
	
	.user-message {
		justify-content: flex-end;
	}
	
	.message-avatar {
		width: 32px;
		height: 32px;
		border-radius: 50%;
		margin: 0 8px;
	}
	
	.message-bubble {
		max-width: 70%;
		padding: 12px 16px;
		border-radius: 18px;
		position: relative;
	}
	
	.ai-message .message-bubble {
		background: white;
		border: 1px solid #e8e8e8;
		border-top-left-radius: 4px;
	}
	
	.user-message .message-bubble {
		background: #6e8efb;
		color: white;
		border-top-right-radius: 4px;
	}
	
	.message-time {
		font-size: 12px;
		color: #999;
		margin-top: 4px;
		text-align: right;
	}
	
	.user-message .message-time {
		color: rgba(255, 255, 255, 0.7);
	}
	
	/* 输入区域 */
	.input-section {
		padding: 15px;
		background: white;
		border-top: 1px solid #eee;
	}
	
	.input-container {
		display: flex;
		align-items: center;
		gap: 10px;
		margin-bottom: 12px;
	}
	
	.input-center {
		flex: 1;
	}
	
	.input-center input {
		width: 100%;
		padding: 12px 15px;
		background: #f5f7fa;
		border-radius: 20px;
		font-size: 14px;
	}
	
	.send-btn {
		width: 40px;
		height: 40px;
		border-radius: 50%;
		background: #6e8efb;
		display: flex;
		align-items: center;
		justify-content: center;
		border: none;
	}
	
	.send-btn:disabled {
		background: #f0f0f0;
	}
	
	/* 快捷问题 */
	.quick-questions {
		margin-top: 10px;
	}
	
	.quick-scroll {
		white-space: nowrap;
	}
	
	.quick-question {
		display: inline-block;
		padding: 8px 16px;
		background: #f0f7ff;
		border: 1px solid #6e8efb;
		border-radius: 16px;
		margin-right: 10px;
		font-size: 12px;
		color: #6e8efb;
	}
	
	/* 加载状态 */
	.loading {
		position: absolute;
		bottom: 80px;
		left: 20px;
		background: white;
		padding: 8px 16px;
		border-radius: 18px;
		display: flex;
		align-items: center;
		gap: 10px;
		box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
	}
	
	.loading-dots {
		display: flex;
		gap: 4px;
	}
	
	.dot {
		width: 6px;
		height: 6px;
		background: #6e8efb;
		border-radius: 50%;
		animation: dotBounce 1.4s infinite ease-in-out;
	}
	
	.dot:nth-child(1) { animation-delay: -0.32s; }
	.dot:nth-child(2) { animation-delay: -0.16s; }
	
	@keyframes dotBounce {
		0%, 80%, 100% { transform: scale(0); }
		40% { transform: scale(1); }
	}
	
	/* 设置面板 */
	.settings-panel {
		background: white;
		border-radius: 20px 20px 0 0;
		padding: 20px;
	}
	
	.panel-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 20px;
		font-size: 18px;
		font-weight: 500;
	}
	
	.setting-item {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 15px 0;
		border-bottom: 1px solid #f0f0f0;
	}
	
	.setting-item:last-child {
		border-bottom: none;
	}
</style>